import axios from "axios";
import { toRaw } from "vue";
import { Message } from "@/components";

const $axios = axios.create({
   baseURL: process.env.BASE_URL,
   headers: {
      "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
   },
   timeout: 150*1000,
});

$axios.interceptors.response.use(
   (response) => {
      const res = response.data;
      if (res.code === 0) {
         return res.data || true
      } else if (res.code === 1032) {
         window.location.href = "/#/login";
      } else {
         if(res.description){
            Message.error(res.description);
         }
      }
   },
   (err) => {
      if(err.code==='ECONNABORTED'){
         Message.error("请求超时，请稍后重试!");
      }else{   
         Message.error("网络请求异常，请稍后重试!");
      }  
   }
);

const isDev =process.env.TYPE==='dev'
export default {
   post(url: string, data?: object) {
      return $axios({
         method: "post",
         url: url + `${isDev?'.json':''}`,
         data: JSON.stringify(Object.assign({}, toRaw(data), { token: localStorage.getItem("token") })),
      });
   },
   get(url: string, data?: object) {
      if(isDev && data){
         console.log('data---',toRaw(data))
      }
      return $axios({
         method: "get",
         url: url + `${isDev?'.json':''}`,
         params: Object.assign({}, toRaw(data), { token: localStorage.getItem("token") }),
      });
   },
   upload(url: string, fb: FormData) {
      return $axios({
         method: process.env.TYPE==='dev'?'get':'post',
         url:url + `${isDev?'.json':''}`,
         data: fb,
         headers: { "Content-Type": "multipart/form-data" },
      });
   },
};
